package com.ims.core.bas.service.impl;

import java.util.List;

import com.ims.common.exception.base.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ims.core.bas.mapper.BasCompanyMapper;
import com.ims.core.bas.domain.BasCompany;
import com.ims.core.bas.service.IBasCompanyService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 公司Service业务层处理
 *
 * @author IMS
 * @date 2024-03-03
 */
@Service
public class BasCompanyServiceImpl implements IBasCompanyService
{
    @Autowired
    private BasCompanyMapper basCompanyMapper;

    /**
     * 查询公司
     *
     * @param companycode 公司主键
     * @return 公司
     */
    @Override
    public BasCompany selectBasCompanyByCompanycode(String companycode)
    {
        return basCompanyMapper.selectBasCompanyByCompanycode(companycode);
    }

    /**
     * 查询公司列表
     *
     * @param basCompany 公司
     * @return 公司
     */
    @Override
    public List<BasCompany> selectBasCompanyList(BasCompany basCompany)
    {
        return basCompanyMapper.selectBasCompanyList(basCompany);
    }

    /**
     * 新增公司
     *
     * @param basCompany 公司
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBasCompany(BasCompany basCompany)
    {
        // 分公司名判重
        BasCompany companyCondition = new BasCompany();
        companyCondition.getParams().put("fullname", basCompany.getCompanyname());
        List<BasCompany> companyList = basCompanyMapper.selectBasCompanyList(companyCondition);
        if(!CollectionUtils.isEmpty(companyList)){
            throw new BaseException("存在同名分公司");
        }

        // 生成分公司编码
        companyCondition = new BasCompany();
        companyList = basCompanyMapper.selectBasCompanyList(companyCondition);
        String companyCode = "0000" + companyList.size();
        companyCode = companyCode.substring(companyCode.length() - 3, companyCode.length());
        basCompany.setCompanycode(companyCode);
        return basCompanyMapper.insertBasCompany(basCompany);
    }

    /**
     * 修改公司
     *
     * @param basCompany 公司
     * @return 结果
     */
    @Override
    public int updateBasCompany(BasCompany basCompany)
    {
        return basCompanyMapper.updateBasCompany(basCompany);
    }

    /**
     * 批量删除公司
     *
     * @param companycodes 需要删除的公司主键
     * @return 结果
     */
    @Override
    public int deleteBasCompanyByCompanycodes(String[] companycodes)
    {
        return basCompanyMapper.deleteBasCompanyByCompanycodes(companycodes);
    }

    /**
     * 删除公司信息
     *
     * @param companycode 公司主键
     * @return 结果
     */
    @Override
    public int deleteBasCompanyByCompanycode(String companycode)
    {
        return basCompanyMapper.deleteBasCompanyByCompanycode(companycode);
    }
}
